{ "cells": [ { "cell_type": "markdown", "metadata": { "pycharm": {} }, "source": [ "# Anonlink Entity Service API\n", "\n", "This tutorial demonstrates interacting with the entity service via the REST API. The primary alternative is to use\n", "a library or command line tool such as [`clkhash`](http://clkhash.readthedocs.io/) which can handle the communication with the anonlink entity service.\n", "\n", "### Dependencies\n", "\n", "In this tutorial we interact with the REST API using the `requests` Python library. Additionally we use the `clkhash` Python library in this tutorial to define the linkage schema and to encode the PII. The synthetic dataset comes from the `recordlinkage` package. All the dependencies can be installed with pip:\n", "\n", "```\n", "pip install requests clkhash recordlinkage\n", "```\n", "\n", "\n", "### Steps\n", "\n", "* Check connection to Anonlink Entity Service\n", "* Synthetic Data generation and encoding\n", "* Create a new linkage project\n", "* Upload the encodings\n", "* Create a run\n", "* Retrieve and analyse results" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [], "source": [ "import json\n", "import os\n", "import time\n", "import requests\n", "\n", "from IPython.display import clear_output" ] }, { "cell_type": "markdown", "metadata": { "pycharm": {} }, "source": [ "## Check Connection\n", "\n", "If you are connecting to a custom entity service, change the address here." ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Testing anonlink-entity-service hosted at https://testing.es.data61.xyz/api/v1/\n" ] } ], "source": [ "server = os.getenv(\"SERVER\", \"https://testing.es.data61.xyz\")\n", "url = server + \"/api/v1/\"\n", "print(f'Testing anonlink-entity-service hosted at {url}')" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [ { "data": { "text/plain": [ "{'project_count': 2278, 'rate': 3863861, 'status': 'ok'}" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "requests.get(url + 'status').json()" ] }, { "cell_type": "markdown", "metadata": { "pycharm": {} }, "source": [ "## Data preparation\n", "\n", "This section won't be explained in great detail as it directly follows the \n", "[clkhash tutorials](http://clkhash.readthedocs.io/en/latest/).\n", "\n", "We encode a synthetic dataset from the `recordlinkage` library using `clkhash`." ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [], "source": [ "from tempfile import NamedTemporaryFile\n", "from recordlinkage.datasets import load_febrl4" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [], "source": [ "dfA, dfB = load_febrl4()" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "with open('a.csv', 'w') as a_csv:\n", " dfA.to_csv(a_csv, line_terminator='\\n')\n", "\n", "with open('b.csv', 'w') as b_csv: \n", " dfB.to_csv(b_csv, line_terminator='\\n')" ] }, { "cell_type": "markdown", "metadata": { "pycharm": {} }, "source": [ "## Schema Preparation\n", "\n", "The linkage schema must be agreed on by the two parties. A hashing schema instructs `clkhash` how to treat each column for encoding PII into CLKs. A detailed description of the hashing schema can be found in the [clkhash documentation](https://clkhash.readthedocs.io/en/latest/schema.html).\n", "\n", "A linkage schema can either be defined as Python code as shown here, or as a JSON file (shown in other tutorials). The importance of each field is controlled by the `k` parameter in the `FieldHashingProperties`.\n", "We ignore the record id and social security id fields so they won't be incorporated into the encoding." ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [], "source": [ "import clkhash\n", "from clkhash.field_formats import *\n", "schema = clkhash.randomnames.NameList.SCHEMA\n", "_missing = MissingValueSpec(sentinel='')\n", "schema.fields = [\n", " Ignore('rec_id'),\n", " StringSpec('given_name', \n", " FieldHashingProperties(ngram=2, k=15)),\n", " StringSpec('surname', \n", " FieldHashingProperties(ngram=2, k=15)),\n", " IntegerSpec('street_number', \n", " FieldHashingProperties(ngram=1, \n", " positional=True, \n", " k=15, \n", " missing_value=_missing)),\n", " StringSpec('address_1', \n", " FieldHashingProperties(ngram=2, k=15)),\n", " StringSpec('address_2', \n", " FieldHashingProperties(ngram=2, k=15)),\n", " StringSpec('suburb', \n", " FieldHashingProperties(ngram=2, k=15)),\n", " IntegerSpec('postcode', \n", " FieldHashingProperties(ngram=1, positional=True, k=15)),\n", " StringSpec('state', \n", " FieldHashingProperties(ngram=2, k=15)),\n", " IntegerSpec('date_of_birth', \n", " FieldHashingProperties(ngram=1, positional=True, k=15, missing_value=_missing)),\n", " Ignore('soc_sec_id')\n", "]" ] }, { "cell_type": "markdown", "metadata": { "pycharm": {} }, "source": [ "## Encoding\n", "\n", "Transforming the *raw* personally identity information into CLK encodings following the defined schema. See the [clkhash](https://clkhash.readthedocs.io/) documentation for further details on this." ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "generating CLKs: 100%|██████████| 5.00k/5.00k [00:02<00:00, 1.78kclk/s, mean=645, std=43.8]\n", "generating CLKs: 100%|██████████| 5.00k/5.00k [00:02<00:00, 1.35kclk/s, mean=634, std=50.3]\n" ] } ], "source": [ "from clkhash import clk\n", "with open('a.csv') as a_pii:\n", " hashed_data_a = clk.generate_clk_from_csv(a_pii, ('key1',), schema, validate=False)\n", " \n", "with open('b.csv') as b_pii:\n", " hashed_data_b = clk.generate_clk_from_csv(b_pii, ('key1',), schema, validate=False)" ] }, { "cell_type": "markdown", "metadata": { "pycharm": {} }, "source": [ "## Create Linkage Project\n", "\n", "The analyst carrying out the linkage starts by creating a linkage project of the desired output type with the Entity Service.\n" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [ { "data": { "text/plain": [ "{'project_id': 'e98ababc1a02a4057a13b39c846e9f219acf71bd0a4143c7',\n", " 'result_token': '693c423c0c021f92a9f7b1658ef8f19beaa7b9c1b27ea22c',\n", " 'update_tokens': ['57401d6c0edfa78abf3bd4a87936159f8c974f93dc352d21',\n", " '8c44139db950ca88f58f18d18e219f001fa105543a7b25e6']}" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "project_spec = {\n", " \"schema\": {},\n", " \"result_type\": \"mapping\",\n", " \"number_parties\": 2,\n", " \"name\": \"API Tutorial Test\"\n", "}\n", "credentials = requests.post(url + 'projects', json=project_spec).json()\n", "\n", "project_id = credentials['project_id']\n", "a_token, b_token = credentials['update_tokens']\n", "credentials" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Note:** the analyst will need to pass on the `project_id` (the \n", "id of the linkage project) and one of the two `update_tokens` to \n", "each data provider.\n", "\n", "The `result_token` can also be used to carry out project API requests:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'error': False,\n", " 'name': 'API Tutorial Test',\n", " 'notes': '',\n", " 'number_parties': 2,\n", " 'parties_contributed': 0,\n", " 'project_id': 'e98ababc1a02a4057a13b39c846e9f219acf71bd0a4143c7',\n", " 'result_type': 'mapping',\n", " 'schema': {}}" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "requests.get(url + 'projects/{}'.format(project_id), \n", " headers={\"Authorization\": credentials['result_token']}).json()" ] }, { "cell_type": "markdown", "metadata": { "pycharm": {} }, "source": [ "Now the two clients can upload their data providing the appropriate *upload tokens*." ] }, { "cell_type": "markdown", "metadata": { "pycharm": {} }, "source": [ "## CLK Upload" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [], "source": [ "a_response = requests.post(\n", " '{}projects/{}/clks'.format(url, project_id),\n", " json={'clks': hashed_data_a},\n", " headers={\"Authorization\": a_token}\n", ").json()" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "b_response = requests.post(\n", " '{}projects/{}/clks'.format(url, project_id),\n", " json={'clks': hashed_data_b},\n", " headers={\"Authorization\": b_token}\n", ").json()" ] }, { "cell_type": "markdown", "metadata": { "pycharm": {} }, "source": [ "Every upload gets a receipt token. In some operating modes this receipt is required to access the results." ] }, { "cell_type": "markdown", "metadata": { "pycharm": {} }, "source": [ "## Create a run\n", "\n", "Now the project has been created and the CLK data has been uploaded we can carry out some privacy preserving record linkage. Try with a few different threshold values:" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [], "source": [ "run_response = requests.post(\n", " \"{}projects/{}/runs\".format(url, project_id),\n", " headers={\"Authorization\": credentials['result_token']},\n", " json={\n", " 'threshold': 0.80,\n", " 'name': \"Tutorial Run #1\"\n", " }\n", ").json()" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [], "source": [ "run_id = run_response['run_id']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Run Status" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'current_stage': {'description': 'compute similarity scores',\n", " 'number': 2,\n", " 'progress': {'absolute': 25000000,\n", " 'description': 'number of already computed similarity scores',\n", " 'relative': 1.0}},\n", " 'stages': 3,\n", " 'state': 'running',\n", " 'time_added': '2019-04-30T12:18:44.633541+00:00',\n", " 'time_started': '2019-04-30T12:18:44.778142+00:00'}" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "requests.get(\n", " '{}projects/{}/runs/{}/status'.format(url, project_id, run_id),\n", " headers={\"Authorization\": credentials['result_token']}\n", " ).json()" ] }, { "cell_type": "markdown", "metadata": { "pycharm": {} }, "source": [ "## Results\n", "\n", "Now after some delay (depending on the size) we can fetch the results. This can of course be done by directly polling the REST API using `requests`, however for simplicity we will just use the watch_run_status function provided in `clkhash.rest_client`.\n", "\n", "> Note the `server` is provided rather than `url`." ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "State: completed\n", "Stage (3/3): compute output\n" ] } ], "source": [ "import clkhash.rest_client\n", "for update in clkhash.rest_client.watch_run_status(server, project_id, run_id, credentials['result_token'], timeout=300):\n", " clear_output(wait=True)\n", " print(clkhash.rest_client.format_run_status(update))\n" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "pycharm": {} }, "outputs": [], "source": [ "data = json.loads(clkhash.rest_client.run_get_result_text(\n", " server, \n", " project_id, \n", " run_id, \n", " credentials['result_token']))" ] }, { "cell_type": "markdown", "metadata": { "pycharm": {} }, "source": [ "This result is the 1-1 mapping between rows that were more similar than the given threshold." ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "a[0] maps to b[1449]\n", "a[1] maps to b[2750]\n", "a[2] maps to b[4656]\n", "a[3] maps to b[4119]\n", "a[4] maps to b[3306]\n", "a[5] maps to b[2305]\n", "a[6] maps to b[3944]\n", "a[7] maps to b[992]\n", "a[8] maps to b[4612]\n", "a[9] maps to b[3629]\n", "...\n" ] } ], "source": [ "for i in range(10):\n", " print(\"a[{}] maps to b[{}]\".format(i, data['mapping'][str(i)]))\n", "print(\"...\")" ] }, { "cell_type": "markdown", "metadata": { "pycharm": {} }, "source": [ "In this dataset there are 5000 records in common. With the chosen threshold and schema we currently retrieve:" ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "pycharm": { "is_executing": false } }, "outputs": [ { "data": { "text/plain": [ "4853" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(data['mapping'])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Cleanup\n", "\n", "If you want you can delete the run and project from the anonlink-entity-service." ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 44, "metadata": {}, "output_type": "execute_result" } ], "source": [ "requests.delete(\n", " \"{}/projects/{}\".format(url, project_id), \n", " headers={\"Authorization\": credentials['result_token']})" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.0" } }, "nbformat": 4, "nbformat_minor": 2 }